<?php
/**
 * @author lan7
 * @since 2010-11-01 00:35
 */
if(!defined('IN_ORA')) {
	exit('Access Denied');
}
$GLOBALS['__msg_tpl__'] = "admin/msg.html";
session_start();
if(!isset($_SESSION["admin"])){
	exit('Access Denied');
}
$act = isset($GLOBALS['act'])?$GLOBALS['act']:'list';
$GLOBALS['tpl']->assign('act',$act);

/////////////////////////////////////////////////////
/** 产品列表  **/
if($act == 'list'){
	$pid = is_numeric($GLOBALS['_param']['p'])?$GLOBALS['_param']['p']:1;
	$psize = $GLOBALS['_param']['psize']?$GLOBALS['_param']['psize']:$GLOBALS['ora_cfg']['page_size'];
	$total = $GLOBALS['db']->count("select count(*) from ".tn('product'));
	import("lib.page");
	$pobj = new page('p',$pid,$total,$psize);
	$sql = "select op.Id,op.pro_name,oc.cat_name,op.pro_pic,op.pro_status,op.pro_views,op.pro_dateline from ".tn("product")." op";
	$sql .=" inner join (select Id from ".tn("product")." order by Id desc limit $pobj->sqlParam) b using(Id)  left join ora_cat oc on op.cat_id = oc.Id  order by op.Id desc";
	if($pid >= intval($pobj->maxPage/2)){
		$sql = "select op.Id,op.pro_name,oc.cat_name,op.pro_pic,op.pro_status,op.pro_views,op.pro_dateline from ".tn("product")." op";
		$sql .=" inner join (select Id from ".tn("product")." order by Id asc limit $pobj->sqlParam) b using(Id)  left join ora_cat oc on op.cat_id = oc.Id order by op.Id desc";
	}
	$pros = $GLOBALS['db']->getAll($sql);
	$GLOBALS['tpl']->assign("pobj",$pobj);
	$GLOBALS['tpl']->assign("pros",$pros);
	$GLOBALS['tpl']->assign('url',preg_replace('/\-?p(\-|_)\d+/i',"",get_urlStr()));
}
/** 添加/修改 **/
else if($act == 'add' || $act == 'modify'){
	/* 获取类别 */
	import("lib.cat");
	$GLOBALS['tpl']->assign('cats',cat_lib::getSubChild(0,3,' and cat_type = 1 '));
	$id = $GLOBALS['_param']['id'];
	if(is_numeric($id)&&$id > 0){
		//修改产品
		import("lib.pro");
		$GLOBALS['tpl']->assign("pro",pro_lib::getPro($id,1,1,1));
	}
	$GLOBALS['tpl']->assign("ptpl",getTpl());
}
/**
 * 保存或新增
 */
else if($act == 'save'){
	$id 		= intval($_POST["pro_id"]);
	$pro_name 	= clear_html($_POST["pro_name"]);
	$pro_keywords 	= clear_html($_POST["keywords"]);
	$pro_tags 		= clear_html($_POST["tags"]);
	$cat_id 	= is_numeric($_POST["cat_id"])?$_POST["cat_id"]:-1;
	$content 	= $_POST["content"];
	/** 属性模板 **/
	$attrKey = $_POST["attrName"];
	$attrVal = $_POST["attrVal"];
	if($pro_name == ""){
		showMsg("请输入产品名称!",$_SERVER["HTTP_REFERER"],1);
	}
	if($cat_id<0){
		showMsg("请选择产品类别!",$_SERVER["HTTP_REFERER"],1);
	}
/*	if($content==""){
		showMsg("请输入产品内容!",$_SERVER["HTTP_REFERER"],1);
	}
 */	/** TODO 添加内链 **/
	$content = htmlspecialchars($content);
	$pro_status = isset($_POST["pro_status"])?1:0;
	$pro_pic = $_POST["pro_pic"];
	$albumId = $_POST["albumId"];
	$coverImage = is_numeric($_POST["coverImage"])?$_POST["coverImage"]:-1;
	/** 图片 **/
	$picDesc = $_POST["uploadText"];
	/** 图片上传 **/
	$images = array();
	import("lib.image");
	import("lib.upload");
	$up = new Upload("jpg|gif|png");
	for ($j=0;$j<sizeof($up->files);$j++){
		$tmp = array();
		if($up->files[$j]['error'] == '0'){
			//上传成功的
			$tmp['url'] = "upload/".$up->files[$j]['urlPath'];
			//添加图片描述信息
			$tmp['desc']= $picDesc[$j];
			//是否为封面图片
			$tmp['cover']= 0;
			if($j==$coverImage){
				$tmp['cover']= 1;
				$pro_pic = $tmp["url"];
			}
			//生成缩略图
			image::thumb(ROOT_PATH.$tmp['url'],'','',100,80);
			$images[] = $tmp;
		}
	}
	if($coverImage == -1){
		if(!empty($images)){
			$pro_pic = $images[0]['url'];
			//默认取第一张图片为封面图片
			$images[0]['cover'] = true;
		}
	}else if(!empty($albumId)){
		$result = $GLOBALS['db']->getOne("select pic from ".tn("album")." where Id = ".$albumId[0]);
		$pro_pic = $result['pic'];
	}

	if($id<=0){
		//新增
		$sql = "insert into ".tn("product")."(cat_id,pro_name,pro_keywords,pro_pic,pro_status,pro_tags,pro_dateline)";
		$sql .=" values($cat_id,'$pro_name','$pro_keywords','$pro_pic',$pro_status,'$pro_tags',".time().")";
		if(!$GLOBALS['db']->execute($sql)){
			/** 清除上传 **/
			foreach ($images as $v) {
				io::remove(ROOT_PATH.$v['url']);//大图
				io::remove(ROOT_PATH.time($v['url']));//缩略图
			}
			showMsg("新增失败!",$_SERVER["HTTP_REFERER"],1);
		}
		$id = $GLOBALS['db']->getLastInsId();
	}else{
		//修改
		$sql = "update ".tn("product")." set cat_id = $cat_id,pro_name = '$pro_name',pro_keywords = '$pro_keywords' ,";
		$sql .=" pro_pic = '$pro_pic',pro_tags='$pro_tags',pro_status = $pro_status,pro_dateline =  ".time()." where Id = $id";
		if(!$GLOBALS['db']->execute($sql)){
			foreach ($images as $v) {
				io::remove(ROOT_PATH.$v['url']);//大图
				io::remove(ROOT_PATH.time($v['url']));//缩略图
			}
			showMsg("修改失败!",$_SERVER["HTTP_REFERER"],1);
		}
	}
	/** 内容处理 **/
	$GLOBALS['db']->execute("delete from ".tn("content")." where ctype=1 and fk_id = $id");
	$GLOBALS['db']->execute("insert into ".tn("content")."(ctype,fk_id,content) values(1,$id,'$content')");

	/** 图片处理 **/

	//更新描述信息
	for ($j=0;$j<sizeof($albumId);$j++){
		if($coverImage == -1 || $coverImage == $j){
			$GLOBALS['db']->execute("update ".tn("album")." set cover = 0 where alb_type =1 and fk_id = $id  ");
			$GLOBALS['db']->execute("update ".tn("album")." set cover = 1,alb_des ='".msubstr($picDesc[$j],0,80)."' where Id=".$albumId[$j]);
			$coverImage = null;
		}else{
			$GLOBALS['db']->execute("update ".tn("album")." set alb_des = '".msubstr($picDesc[$j],0,80)."' where Id = ".$albumId[$j]);
		}
	}
	if(is_array($albumId)&&!empty($albumId)){
		$albumIdstr = implode(",",$albumId);
	}else{
		$albumIdstr = 0;
	}
	$GLOBALS['db']->execute("delete from ".tn("album")." where alb_type = 1 and fk_id = $id and id not in ($albumIdstr)");
	foreach ($images as $k => $v){
		$sql  = "insert into ".tn("album")."(alb_name,alb_type,fk_id,pic,alb_des,alb_date,cover) ";
		$sql .= " values('$pro_name',1,$id,'{$v['url']}','{$picDesc[sizeof($albumId)+$k]}',".time().",0)";
		$GLOBALS['db']->execute($sql);
	}

	/** 标签处理 **/
	$GLOBALS['db']->execute("delete from ".tn("tags")." where tag_type = 1 and  fk_id = $id");
	$pro_tags = explode(",",$pro_tags);
	if(!empty($pro_tags)){
		foreach ($pro_tags as $v) {
			if($v!=""){
				$GLOBALS['db']->execute("insert into ".tn("tags")."(tag_type,fk_id,tag_name) values(1,$id,'$v')");
			}
		}
	}
	/** 属性处理 **/
	$attr = array();
	if(!empty($attrKey)&&!empty($attrVal)){
		$tmp = array();
		$tmp["key"] = $attrKey;
		$tmp["val"] = $attrVal;
		$attr = $tmp;
	}
	$attrStr = serialize($attr);
	$GLOBALS['db']->execute("delete from ".tn("pattr")." where p_id = $id");
	$GLOBALS['db']->execute("insert into ".tn("pattr")."(p_id,attr) values($id,'$attrStr')");
	showMsg("操作成功!",parse_uri("admin_case-list|true"),1);

}
/**
 * 删除产品
 */
else if($act == 'del'){
	$id = isset($GLOBALS['_param']['id'])?$GLOBALS['_param']['id']:$_POST["id"];
	if(is_array($id)){
		$idstr = implode(",",$id);
		$GLOBALS['db']->execute("delete from ".tn("content")." where ctype=1 and fk_id in($idstr)");
		/** 删除属性 **/
		$GLOBALS['db']->execute("delete from ".tn("pattr")." where p_id in ($idstr)");
		/** 删除图集 **/
		$pics = $GLOBALS['db']->getAll("select pic from  ".tn("album")." where alb_type = 1 and fk_id in ($idstr)");
		/** 删除图片文件 **/
		for ($i=0;$i<sizeof($pics);$i++){
			io::remove(ROOT_PATH.$pics[$i]["pic"]);
			io::remove(ROOT_PATH.timg($pics[$i]["pic"]));
		}
		$GLOBALS['db']->execute("delete from ".tn("album")." where alb_type = 1 and fk_id in ( $idstr)");
		$GLOBALS['db']->execute("delete from ".tn("product")." where Id in ( $idstr)");
		/** 删除标签 **/
		$GLOBALS['db']->execute("delete from ".tn("tags")." where tag_type = 1 and fk_id in ( $idstr)");
		
	}else{
		$id = intval($id);
		if($id>0){
			/** 删除内容 **/
			$GLOBALS['db']->execute("delete from ".tn("content")." where ctype=1 and fk_id = $id");
			/** 删除属性 **/
			$GLOBALS['db']->execute("delete from ".tn("pattr")." where p_id = $id");
			/** 删除图集 **/
			$pics = $GLOBALS['db']->getAll("select pic from  ".tn("album")." where alb_type = 1 and fk_id = $id");
			/** 删除图片文件 **/
			for ($i=0;$i<sizeof($pics);$i++){
				io::remove(ROOT_PATH.$pics[$i]["pic"]);
				io::remove(ROOT_PATH.timg($pics[$i]["pic"]));
			}
			$GLOBALS['db']->execute("delete from ".tn("album")." where alb_type = 1 and fk_id = $id");
			$GLOBALS['db']->execute("delete from ".tn("product")." where Id = $id");
			/** 删除标签 **/
			$GLOBALS['db']->execute("delete from ".tn("tags")." where tag_type = 1 and fk_id =  $id ");
		}
	}
	showMsg("操作成功!",parse_uri("admin_case-list|true"),1);
}
/** 审核文章 **/
else if($act == 'pass'){
	$id = $_POST["id"];
	if($id!=""&&is_array($id)){
		$id = array_filter($id,"filt");
		$GLOBALS['db']->execute("update ".tn("product")." set status = 1 where Id in (".implode(",",$id).")");
		showMsg("审核成功!",parse_uri("admin_article-list"),1);
	}
	showMsg("请选择待审核的产品!",parse_uri("admin_article-list"),1);
}
$GLOBALS['tpl']->display("admin/case.html");

//////////////////////////////////////////
/** 获取类型模板 **/
function getTpl(){
	$result = array();
	$query = $GLOBALS['db']->query("select * from ".tn("ptpl")." order by Id desc");
	while ($row = $GLOBALS['db']->fetch_array($query)) {
		$row['tpl'] = unserialize($row['tpl']);
		$result[] = $row;
	}
	return $result;
}
/** 过滤非数字元素 **/
function filt($v){
	return is_numeric($v);
}
?>
